package com.hui10.mediaplayer.base

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import com.hui10.mediaplayer.widget.LoadMoreView

/**
 * Author: Created by lucus on 2019/5/30.
 * E-mail: mcphilex1989@gmail.com
 * Tel: 15652608401
 */
abstract class BaseListAdapter<ITEMBEAN, ITEMVIEW : View> : RecyclerView.Adapter<BaseListAdapter.BaseListViewHolder>() {

    private var list = ArrayList<ITEMBEAN>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseListViewHolder {
        if (viewType == 1) {
            return BaseListViewHolder(LoadMoreView(parent.context))
        }
        return BaseListViewHolder(getItemView(parent.context))
    }

    override fun getItemCount(): Int {
        return this.list.size + 1 // 添加底部加载更多view
    }

    override fun getItemViewType(position: Int): Int {
        if (position == list.size) {
            return 1
        }
        return 0
    }

    override fun onBindViewHolder(holder: BaseListViewHolder, position: Int) {
        val type = getItemViewType(position)
        if (type == 1) return
        val baseItemView = holder.itemView as ITEMVIEW
        val baseItemBean = this.list[position]
        refreshItemViewData(baseItemView, baseItemBean)
    }

    class BaseListViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

    abstract fun refreshItemViewData(itemView: ITEMVIEW, itemBean: ITEMBEAN)

    abstract fun getItemView(context: Context?): ITEMVIEW

    fun notifyDataChanged(type: Int, list: List<ITEMBEAN>?) {
        when (type) {
            BasePresenter.DATA_INIT_OR_REFRESH -> {
                list?.let {
                    this.list.clear()
                    this.list.addAll(list)
                }
            }
            BasePresenter.DATA_LOAD_MORE -> {
                list?.let {
                    this.list.addAll(list)
                }
            }
        }
        notifyDataSetChanged()
    }
}